package com.miaoshapro.controller;

import com.miaoshapro.error.ErrorEnum;
import com.miaoshapro.exception.CommonException;
import com.miaoshapro.response.CommonResponse;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

public class BaseController {

    public final String CONTENT_TYPE = "application/x-www-form-urlencoded";

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public CommonResponse handleException(HttpServletRequest request, Exception exception) {
        Map<String, Object> responseData = new HashMap<>();
        if (exception instanceof CommonException) {
            CommonException commonException = (CommonException)exception;
            responseData.put("errorCode", commonException.getErrorCode());
            responseData.put("errorMsg", commonException.getErrorMsg());
        } else {
            System.out.println(exception);
            responseData.put("errorCode", ErrorEnum.UNKNOW_ERROR.getErrorCode());
            responseData.put("errorMsg", ErrorEnum.UNKNOW_ERROR.getErrorMsg());
        }
        return CommonResponse.create("error", responseData);
    }
}
